package com.wangjie.pattern.proxy.utils;

import sun.misc.ProxyGenerator;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author jieshao
 * @date 2022/6/22 1:04
 */
public class ProxyUtils {
    public static void saveClassFile(Class clazz, String proxyName) {
        // 生成 class 的字节数组, 此处生成的 class 与 Proxy.newProxyInstance 中生成的 class 除了代理类的名字不同, 其它内容完全一致
        byte[] classFile = ProxyGenerator.generateProxyClass(proxyName, clazz.getInterfaces());
        String path = clazz.getResource(".").getPath();
        String fileName = path + proxyName + ".class";
        System.out.println("fileName: " + fileName);
        FileOutputStream out = null;
        try {
            // 保存到磁盘
            out = new FileOutputStream(fileName);
            out.write(classFile);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}